import { type AlovaGenerics, type AlovaOptions, createAlova } from 'alova'
import { createClientTokenAuthentication, useCaptcha, useForm, useRequest, useRetriableRequest } from 'alova/client'
import adapterFetch from 'alova/fetch'
import VueHook from 'alova/vue'

export * from 'alova/client'

const { onAuthRequired, onResponseRefreshToken } = createClientTokenAuthentication({
  // refreshToken: {
  //   // 在请求前触发，将接收到method参数，并返回boolean表示token是否过期
  //   isExpired: method => {
  //     return tokenExpireTime < Date.now();
  //   },
  //
  //   // 当token过期时触发，在此函数中触发刷新token
  //   handler: async method => {
  //     try {
  //       const { token, refresh_token } = await refreshToken();
  //       localStorage.setItem('token', token);
  //       localStorage.setItem('refresh_token', refresh_token);
  //     } catch (error) {
  //       // token刷新失败，跳转回登录页
  //       location.href = '/login';
  //       // 并抛出错误
  //       throw error;
  //     }
  //   }
  // }
})

type Meta = {
  showMsg?: boolean
}
export function createRequest(id: string, options?: AlovaOptions<AlovaGenerics>) {
  return createAlova({
    id,
    baseURL: window.appConfig.baseURL || '',
    requestAdapter: adapterFetch(),
    statesHook: VueHook,
    shareRequest: true,
    // cacheFor: new Date('2030-01-01'),
    cacheLogger: true,
    ...options,
    // ...
    beforeRequest: onAuthRequired(method => {
      console.log(method)
      console.log(method.config.headers)
      // ...原请求前拦截器
    }),
    responded: onResponseRefreshToken({
      onSuccess: async (response, method) => {
        const meta: Meta = method.meta
        // ...原响应成功拦截器
        const res = await response.json()
        if (meta?.showMsg) {
          if (res.code === 1) {
            // 弹出成功消息
          } else {
            // 弹出错误消息
          }
          return res.data
        }
        return res
      },
      onError: (error, method) => {
        // ...原响应错误拦截器
        console.log(2, error)
      },
      onComplete: method => {
        // ...原响应完成拦截器
        // console.log(3,method)
      },
    }),
  })
}

const apiInstance = createRequest('common')

export const cacheInstance = createRequest('cache', {})

/**
 * 发送短信验证码
 *
 * @param {string} url url地址
 * @param {string | number} mobile 手机号
 * @param {number} initialCountdown 倒计时
 */
export function sendCaptcha(url: string, mobile: string | number, initialCountdown: number = 30) {
  return useCaptcha(
    apiInstance.Post(url, {
      mobile,
    }),
    {
      // 默认将倒计时设为30秒
      initialCountdown,
    },
  )
}

export default apiInstance
